<?php

declare(strict_types=1);

namespace Plugin\Attractions\AttractionManagement\Repository;

use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
use Plugin\Attractions\AttractionManagement\Model\AttractionInfoTag;

class AttractionInfoTagRepository extends IRepository
{
    public function __construct(protected readonly AttractionInfoTag $model) {}

    public function handleSearch(Builder $query, array $params): Builder
    {
        return $query
            ->when(Arr::get($params, 'infoId'), static function (Builder $query, $info_id) {
                $query->whereIn('info_id', Arr::wrap($info_id));
            })
            ->when(Arr::get($params, 'sort'), static function (Builder $query, $sort) {
                $query->orderBy('info_id', 'asc')->orderBy('sort', $sort == 0 ? 'asc' : 'desc');
            });
    }

    public function list(array $params = []): Collection
    {
        return $this->perQuery($this->getQuery(), $params)
            ->get(['info_id', 'tag', 'sort']);
    }

    public function insert(array $data, int $infoID) 
    {
        foreach ($data as &$item) {
            $item['info_id'] = $infoID;
        }
        return $this->getQuery()->insert($data);
    }

    public function deleteByInfoId(array $infoId): int
    {
        return $this->getQuery()->whereIn('info_id', $infoId)->delete();
    }
}